package com.laiketui.common.service.dubbo.plugin;

import com.laiketui.common.mapper.*;
import com.laiketui.domain.lktconst.ErrorCode;
import com.laiketui.domain.order.BargainOrderModel;
import com.laiketui.domain.order.OrderModel;
import com.laiketui.domain.plugin.bargain.BargainConfigModel;
import com.laiketui.domain.product.ProductListModel;
import com.laiketui.domain.user.User;
import com.laiketui.common.api.PubliceService;
import com.laiketui.common.api.plugin.PubliceBargainService;
import com.laiketui.core.diyJavaFunction.StringUtils;
import com.laiketui.core.exception.LaiKeAPIException;
import com.laiketui.core.lktconst.DictionaryConst;
import com.laiketui.core.lktconst.GloabConst;
import com.laiketui.core.utils.tool.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 公共砍价
 *
 * @author Trick
 * @date 2021/2/22 16:19
 */
@Service
public class PubliceBargainServiceImpl implements PubliceBargainService {
    private final Logger logger = LoggerFactory.getLogger(PubliceBargainServiceImpl.class);

    @Autowired
    private BargainGoodsModelMapper bargainGoodsModelMapper;

    @Autowired
    private BargainConfigModelMapper bargainConfigModelMapper;

    @Autowired
    private ProductListModelMapper productListModelMapper;

    @Autowired
    private BargainOrderModelMapper bargainOrderModelMapper;

    @Autowired
    private BargainRecordModelMapper bargainRecordModelMapper;

    @Autowired
    private OrderModelMapper orderModelMapper;

    @Autowired
    private PubliceService publiceService;

    @Override
    public List<Map<String, Object>> bargainGoodsInfo(int storeId, int pageStart, int pageEnd, User user) throws LaiKeAPIException {
        List<Map<String, Object>> resultList;
        try {
            //砍价开始时间
            Date startDate = new Date();
            //砍价结束时间
            Date endDate = new Date();

            //获取砍价设置
            BargainConfigModel bargainConfigModel = new BargainConfigModel();
            bargainConfigModel.setStore_id(storeId);
            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
            if (bargainConfigModel != null) {
                //商品活动结束后显示的时间 单位/时
                Integer showDay = bargainConfigModel.getShow_time();
                //时转秒
                int second = DateUtil.dateConversion(showDay, DateUtil.TimeType.TIME);
                //结束后持续可见的秒数
                endDate = DateUtil.getAddDateBySecond(new Date(), -second);
            }
            resultList = bargainGoodsModelMapper.selectBargainGoodsInfo(storeId, startDate, endDate, pageStart, pageEnd);
            for (Map<String, Object> map : resultList) {
                int goodsId = Integer.parseInt(map.get("goods_id").toString());
                int attrId = Integer.parseInt(map.get("attr_id").toString());
                int bargainId = Integer.parseInt(map.get("bargain_id").toString());
                //获取商品金额
                BigDecimal goodsPrice = new BigDecimal(map.get("price").toString());
                //获取砍价金额
                BigDecimal goodsBargainPrice = new BigDecimal(map.get("min_price").toString());
                //获取商品信息
                ProductListModel productListModel = new ProductListModel();
                productListModel.setId(goodsId);
                productListModel = productListModelMapper.selectOne(productListModel);
                if (productListModel != null) {
                    map.put("title", productListModel.getProduct_title());
                    map.put("img", publiceService.getImgPath(map.get("img").toString(), storeId));
                    Date endTime = DateUtil.dateFormateToDate(map.get("end_time").toString(), GloabConst.TimePattern.YMDHMS);
                    Date startTime = DateUtil.dateFormateToDate(map.get("begin_time").toString(), GloabConst.TimePattern.YMDHMS);
                    if (endTime == null || startTime == null) {
                        continue;
                    }
                    //定义 天 时 分 秒
                    String day, time, mniuate, second;
                    //标记活动开始
                    int isbegin = 1;
                    //前台倒计时变量
                    long surplusSecond;
                    //判断活动是否启动
                    if (DateUtil.dateCompare(startTime, new Date())) {
                        //活动未启动
                        isbegin = 0;
                        //计算活动距离开始时间秒数
                        surplusSecond = (startTime.getTime() / 1000 - DateUtil.getTime());
                    } else {
                        //计算活动剩余时间/s
                        surplusSecond = (endTime.getTime() / 1000 - DateUtil.getTime());
                    }
                    map.put("isbegin", isbegin);
                    map.put("leftTime", surplusSecond);
                    //时间处理
                    String temp = DateUtil.dateConversion(surplusSecond, DateUtil.TimeType.DAY) + "";
                    day = StringUtils.isEmpty(temp) ? "0" : temp;
                    temp = DateUtil.dateConversion(surplusSecond, DateUtil.TimeType.TIME) + "";
                    time = StringUtils.isEmpty(temp) ? "00" : temp;
                    temp = DateUtil.dateConversion(surplusSecond, DateUtil.TimeType.MINUTE) + "";
                    mniuate = StringUtils.isEmpty(temp) ? "00" : temp;
                    temp = DateUtil.dateConversion(surplusSecond, DateUtil.TimeType.SECOND) + "";
                    second = StringUtils.isEmpty(temp) ? "00" : temp;

                    map.put("day", day);
                    map.put("hour", time);
                    map.put("mniuate", mniuate);
                    map.put("second", second);
                    map.put("status", 0);
                    map.remove("id");
                    map.remove("begin_time");
                    map.remove("end_time");
                    // 当用户登录时 查询用户是否存在订单 status -1.砍价失败 0.未开始砍价 1.砍价中 2.砍价成功 3.已付款
                    if (user != null) {
                        //获取订单信息
                        BargainOrderModel bargainOrderModel = bargainOrderModelMapper.getUserBargainOrder(storeId, bargainId, user.getUser_id(), goodsId, attrId);
                        if (bargainOrderModel != null) {
                            map.put("order_no", bargainOrderModel.getOrder_no());
                            //-1/-2.砍价失败 0.未开始砍价 1.砍价中 2.砍价成功 3.已付款
                            int status = -2;
                            // 是否已经创建订单 1.是
                            map.put("hasorder", 1);
                            map.put("sNo_id", bargainOrderModel.getId());
                            if (bargainOrderModel.getStatus() == 0) {
                                status = 1;
                                //已砍金额
                                BigDecimal orderAmt = bargainRecordModelMapper.getOrderMoney(storeId, bargainOrderModel.getOrder_no());
                                map.put("priceDown", orderAmt);
                                //计算剩余金额
                                goodsPrice = goodsPrice.subtract(orderAmt).subtract(goodsBargainPrice);
                                map.put("priceleft", goodsPrice);
                            } else if (bargainOrderModel.getStatus() == 1) {
                                //砍价成功
                                status = 2;
                                OrderModel orderModel = orderModelMapper.getNotCloseOrdersByNo(bargainOrderModel.getOrder_no());
                                if (orderModel != null) {
                                    if (orderModel.getStatus().equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID)) {
                                        map.put("gopay", 1);
                                        // 后台设置结算时间大于0时
                                        if (bargainConfigModel != null && bargainConfigModel.getBuy_time() > 0) {
                                            if (bargainOrderModelMapper.isBargainEnd(bargainOrderModel.getOrder_no(), Long.parseLong(bargainConfigModel.getBuy_time() + "")) > 0) {
                                                status = -1;
                                            }
                                        }
                                    } else {
                                        status = 3;
                                    }
                                }
                            } else if (bargainOrderModel.getStatus() == 2) {
                                status = 3;
                            }
                            map.put("status", status);
                        }
                    }
                }
            }
        } catch (LaiKeAPIException l) {
            throw l;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取正在砍价商品信息 异常" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "bargainGoodsInfo");
        }
        return resultList;
    }


    /**
     * 获取砍价商品详情
     *
     * @param storeId   -
     * @param bargainId -
     * @return List
     * @author Trick
     * @date 2021/4/20 15:20
     */
    @Override
    public Map<String, Object> getBargainDataList(int storeId, int bargainId, User user) {
        Map<String, Object> resultMap = new HashMap<>(16);
        try {
            //获取商品出售数量
            BargainOrderModel bargainOrderModel = new BargainOrderModel();
            bargainOrderModel.setStore_id(storeId);
            bargainOrderModel.setBargain_id(bargainId);
            int volume = bargainOrderModelMapper.selectCount(bargainOrderModel);

            BigDecimal goodsPrice = new BigDecimal("0");
            BigDecimal goodsBargainPrice = new BigDecimal("0");
            //砍价开始时间
            Date startDate = new Date();
            //砍价结束时间
            Date endDate = new Date();
            //获取砍价设置
            BargainConfigModel bargainConfigModel = new BargainConfigModel();
            bargainConfigModel.setStore_id(storeId);
            bargainConfigModel = bargainConfigModelMapper.selectOne(bargainConfigModel);
            if (bargainConfigModel != null) {
                //商品活动结束后显示的时间 单位/时
                Integer showDay = bargainConfigModel.getShow_time();
                //时转秒
                int second = DateUtil.dateConversion(showDay, DateUtil.TimeType.TIME);
                //结束后持续可见的秒数
                endDate = DateUtil.getAddDateBySecond(new Date(), -second);
            }
            List<Map<String, Object>> bargainGoodsInfoList = bargainGoodsModelMapper.selectBargainGoodsInfo(storeId, startDate, endDate, 0, 1);
            for (Map<String, Object> goodsInfo : bargainGoodsInfoList) {
                goodsInfo.put("title", goodsInfo.get("product_title"));
                goodsInfo.put("img", publiceService.getImgPath(goodsInfo.get("img").toString(), storeId));

                int goodsId = Integer.parseInt(goodsInfo.get("goods_id").toString());
                int attrId = Integer.parseInt(goodsInfo.get("attr_id").toString());
                //获取商品金额
                goodsPrice = new BigDecimal(goodsInfo.get("price").toString());
                //获取砍价金额
                goodsBargainPrice = new BigDecimal(goodsInfo.get("min_price").toString());
                Date startTime = DateUtil.dateFormateToDate(goodsInfo.get("begin_time").toString(), GloabConst.TimePattern.YMDHMS);
                Date endTime = DateUtil.dateFormateToDate(goodsInfo.get("end_time").toString(), GloabConst.TimePattern.YMDHMS);
                if (endTime == null || startTime == null) {
                    continue;
                }
                //标记活动开始
                int isbegin = 1;
                //前台倒计时变量
                long surplusSecond = endTime.getTime() / 1000 - DateUtil.getTime();
                //判断活动是否启动
                if (DateUtil.dateCompare(startTime, new Date())) {
                    //活动未启动
                    isbegin = 0;
                    //计算活动距离开始时间秒数
                    surplusSecond = startTime.getTime() / 1000 - DateUtil.getTime();
                }
                // 当用户登录时 查询用户是否存在订单 status -1.砍价失败 0.未开始砍价 1.砍价中 2.砍价成功 3.已付款
                if (user != null) {
                    //获取订单信息
                    bargainOrderModel = bargainOrderModelMapper.getUserBargainOrder(storeId, bargainId, user.getUser_id(), goodsId, attrId);
                    if (bargainOrderModel != null) {
                        goodsInfo.put("order_no", bargainOrderModel.getOrder_no());
                        //-1/-2.砍价失败 0.未开始砍价 1.砍价中 2.砍价成功 3.已付款
                        int status = -2;
                        // 是否已经创建订单 1.是
                        goodsInfo.put("hasorder", 1);
                        goodsInfo.put("sNo_id", bargainOrderModel.getId());
                        if (bargainOrderModel.getStatus() == 0) {
                            status = 1;
                            //已砍金额
                            BigDecimal orderAmt = bargainRecordModelMapper.getOrderMoney(storeId, bargainOrderModel.getOrder_no());
                            goodsInfo.put("priceDown", orderAmt);
                            //计算剩余金额
                            goodsPrice = goodsPrice.subtract(orderAmt).subtract(goodsBargainPrice);
                            goodsInfo.put("priceleft", goodsPrice);
                        } else if (bargainOrderModel.getStatus() == 1) {
                            //砍价成功
                            status = 2;
                            OrderModel orderModel = orderModelMapper.getNotCloseOrdersByNo(bargainOrderModel.getOrder_no());
                            if (orderModel != null) {
                                if (orderModel.getStatus().equals(DictionaryConst.OrdersStatus.ORDERS_R_STATUS_UNPAID)) {
                                    goodsInfo.put("gopay", 1);
                                    // 后台设置结算时间大于0时
                                    if (bargainConfigModel != null && bargainConfigModel.getBuy_time() > 0) {
                                        if (bargainOrderModelMapper.isBargainEnd(bargainOrderModel.getOrder_no(), Long.parseLong(bargainConfigModel.getBuy_time() + "")) > 0) {
                                            status = -1;
                                        }
                                    }
                                } else {
                                    status = 3;
                                }
                            }
                        } else if (bargainOrderModel.getStatus() == 2) {
                            status = 3;
                        }
                        goodsInfo.put("status", status);
                    }
                }
                goodsInfo.put("isbegin", isbegin);
                goodsInfo.put("leftTime", surplusSecond);
            }
            resultMap.put("bargain_info", bargainGoodsInfoList);
            resultMap.put("cs_num", volume);
            resultMap.put("cs_yprice", goodsBargainPrice);
            resultMap.put("cs_price", goodsPrice);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("砍价商品详情" + e.getMessage());
            throw new LaiKeAPIException(ErrorCode.BizErrorCode.ERROR_CODE_WLYC, "网络异常", "getBargainDataList");
        }
        return resultMap;
    }
}

